const fetch = require('node-fetch')
const VirtualModulesPlugin = require('webpack-virtual-modules')
const logger = require('./logger')('CustomTenantsPlugin')

class CustomTenantsPlugin {
	constructor() {
		logger.log('initializing...')

		Object.assign(this, {
			tenants: [],
		}, ...arguments)
	}

	apply(compiler) {
		this.virtualModule = new VirtualModulesPlugin()
		this.virtualModule.apply(compiler)

		const { name } = this.constructor

		compiler.hooks.compilation.tap(name, compilation => {
			const { Compilation } = compiler.webpack
			const stage = Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL

			compilation.hooks.processAssets.tapPromise({ name, stage }, async () => {
				this.handleProcessAssets(compilation)
			})
		})
	}

	async fetchOkapiOptions() {
		try {
			if (!this.url) {
				throw new Error('Url must be a valid value')
			}
			const response = await fetch(this.url, {
				headers: { 'X-Okapi-Tenant': 'null' }
			})
			const { data } = await response.json()
			return data
		} catch (error) {
			return []
		}
	}

	async handleProcessAssets(compilation) {
		try {
			this.tenants = await this.fetchOkapiOptions()
			const virtualContent = `export default ${JSON.stringify(this.tenants)}`

			if (this.cachedVirtualContent !== virtualContent) {
				logger.log('writing virtual module...', virtualContent)

				this.virtualModule.writeModule('node_modules/yunhan-tenants-config.js', virtualContent)
				this.cachedVirtualContent = virtualContent
			}
		} catch (error) {
			compilation.errors.push(error)
		}
	}
}

module.exports = CustomTenantsPlugin
